package com.Hot100;

import java.util.*;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/4/23 15:37
 * @description
 */
public class DayTwo {

    public static void main(String[] args) {
        threeSum(new int[]{-1, 0, 1, 2, -1, -4});
    }

    //三数之和
    //满足 i != j、i != k 且 j != k ，同时还满足 nums[i] + nums[j] + nums[k] == 0
    //你返回所有和为 0 且不重复的三元组。
    public static List<List<Integer>> threeSum(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            for (int k = 0; k < nums.length; k++) {
                if (map.containsKey(-(nums[i] + nums[k])) && i != k) {
                    Integer index = map.get(-(nums[i] + nums[k]));
                    if (index != i && index != k) {
                        ArrayList<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[k]);
                        list.add(nums[index]);
                        list.sort(Comparator.comparingInt(a -> a));
                        if (!result.contains(list)) {
                            result.add(list);
                        }
                    }
                }
            }
        }
        return result;
    }
}
